<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\Collection as CollectionModel;
use app\payment\model\PaymentCash as PaymentCashModel;
use app\payment\model\Download as DownloadModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 收款控制器
 */
class Collection extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'see', 'add', 'export'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        $all_collection_status = [0 => '申请充值', 1 => '充值成功', 2 => '驳回', 8 => '程序员查看'];
        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = CollectionModel::where($map)->order('create_time desc')->paginate($list_rows);

        $sum_count = CollectionModel::where($map)->count();
        $sum_cash = CollectionModel::where($map)->sum('cash');
        $sum_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        $date = date('Y-m-d');
        $search = [
            ['daterange:6', 'create_time', '发起时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '充值状态', '', '', $all_collection_status],
            ['select:3', 'collection_type', '充值类型', '', '', ['0' => '银行卡', '1' => '支付宝']],
            // ['text:3', 'out_card', '付款银行卡'],
            // ['text:3', 'out_name', '付款人姓名'],
            // ['text:3', 'enter_card', '收款银行卡'],
            // ['text:3', 'enter_name', '收款人姓名'],
            ['text:3', 'order_id', '平台订单号'],
            ['text:3', 'cash', '充值金额'],
            ['select:3', 'mode', '到账方式', '', '', ['0' => '剩余余额', '1' => '代付余额']],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'operation_id', '操作号'],
            ['text:3', 'merchant_id', '商户号'],
        ];

        $items = [
            ['operation_id', '操作', 'callback', function ($value) {
                return $value ? $value . '<br/>' . get_user_nickname($value) : '';
            }, '', 'text-center'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['order_id', '平台订单号'],
            // ['out_name', '付款人姓名'],
            // ['out_card', '付款银行卡'],
            // ['enter_name', '收款人姓名'],
            // ['enter_card', '收款银行卡'],
            ['cash', '充值金额（元）', 'callback', function ($cash) {
                return $cash / 100;
            }],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '充值状态', 'status', '', $all_collection_status],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[6]);
            unset($search[7]);
            unset($search[8]);
            // 去掉显示列
            unset($items[0]);
            unset($items[1]);
        }
        if ($this->is_agent) {
            // 显示搜索项
            $search[] = ['text:3', 'merchant_id', '商户号'];
            // 显示列
            array_unshift($items, ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center']);
        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    总金额：{$sum_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $add_collection = <<<EOF
<a title="申请充值" style="margin-bottom:6px;" class="btn btn-nm btn-primary" href="add" >
<i class="fa fa-plus-circle"></i>
申请充值
</a> 
EOF;

        $tips = '';
        if (!$this->no_auth) {
            $collection_count = CollectionModel::where(['status' => 0])->count();
            $collection_count_cash = CollectionModel::where(['status' => 0])->sum('cash');
            $collection_count_cash /= 100;
            if ($collection_count > 0) {
                $tips = "<font size='3' color='#f0ad4e'>申请充值有{$collection_count}个，总金额为{$collection_count_cash}元！</font>";
            }
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('充值列表') // 设置页面标题
            ->setTableName('payment_collection') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->setSearchArea($search) // 设置搜索参数
            ->setPageTips($tips)
            ->hideCheckbox()
            ->addColumns($items)
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->setExtraHtml($add_collection, 'toolbar_top')
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->replaceRightButton(['status' => ['not in', '0,3,4']], '', 'edit') // 替换右侧按钮
            ->fetch(); // 渲染页面
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        $all_collection_status = [0 => '申请充值', 1 => '充值成功', 2 => '驳回', 8 => '程序员查看'];

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = CollectionModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！');
        }

        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "收款订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'operation_id',
            'merchant_id',
            'out_name',
            'out_card',
            'enter_name',
            'enter_card',
            'collection_type',
            'mode',
            'cash',
            'status',
            'order_id',
            'other_order_id',
            'create_time',
            'update_time',
        ];
        if ($this->no_auth) {
            unset($field[0]);
            unset($field[11]);
        }

        $cellName = [
            '操作号',
            '商户号',
            '付款人姓名',
            '付款银行卡',
            '收款人姓名',
            '收款银行卡',
            '充值类型',
            '到账方式',
            '充值金额',
            '充值状态',
            '本地订单号',
            '第三方订单号',
            '创建时间',
            '更新时间',
        ];
        if ($this->no_auth) {
            unset($cellName[0]);
            unset($cellName[11]);
        }
        $hide_info = 0;
        if ($this->no_auth) {
            $hide_info = 1;
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_collection')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_collection_status, $hide_info) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;

                    $single['status'] = $all_collection_status[$single['status']];
                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;
                    $single['collection_type'] = $single['collection_type'] == 1 ? '支付宝' : '银行卡';
                    $single['mode'] = $single['mode'] == 1 ? '代付余额' : '剩余余额';

                    if ($hide_info) {
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }

            // 验证
            $result = $this->validate($data, 'Collection');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            $data['cash'] *= 100;                                        // 金额
            $data['status'] = 0;                                         // 充值状态
            $data['order_id'] = date('ymdHis') . random(8);              // 平台订单号
            $data['create_time'] = time();                               // 创建时间
            $data['update_time'] = time();                               // 更新时间

            if ($temp = CollectionModel::create($data)) {

                // 记录行为
                action_log('payment_collection_add', 'collection', $temp['order_id'], UID, json_encode($temp));
                $this->success('新增成功！', url('index'));
            } else {
                $this->error('新增失败！');
            }
        }

        $items = [
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['radio', 'collection_type', '充值类型', '', ['0' => '银行卡', '1' => '支付宝'], '0'],
            ['radio', 'mode', '到账方式', '', ['0' => '剩余余额', '1' => '代付余额'], '1'],
            // ['text', 'out_name', '付款人姓名', '必填：比如:<code>我是谁</code>'],
            // ['text', 'out_card', '付款银行卡', '必填：比如:<code>6217002870051515818</code>'],
            // ['text', 'enter_name', '收款人姓名', '必填：比如:<code>我是谁</code>'],
            // ['text', 'enter_card', '收款银行卡', '必填：比如:<code>6217002870051515818</code>'],
            ['text', 'cash', '充值金额', '必填（整数）：比如:<code>10000</code>', 0],
            ['textarea', 'merchant_remark', '商户备注'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->no_auth) {
            unset($items[0]);
        }

        $tips = "请勿填错！";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('申请充值') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数');
        }
        $all_collection_status = [0 => '申请充值', 1 => '充值成功', 2 => '驳回', 8 => '程序员查看'];
        // 获取数据
        $info = CollectionModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if (in_array($info['merchant_id'], $sub_merchant)) {
                $see_auth = true;
            }
        }

        if ($this->no_auth) {
            if (!isset($see_auth) && $this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        $info['cash'] /= 100;

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            // ['static', 'out_name', '付款人姓名'],
            // ['static', 'out_card', '付款银行卡'],
            // ['static', 'enter_name', '收款人姓名'],
            // ['static', 'enter_card', '收款银行卡'],
            ['textarea', 'merchant_remark', '商户备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '充值状态', '', $all_collection_status, '', '', 'disabled'],
            ['radio', 'collection_type', '充值类型', '', ['银行卡', '支付宝'], '', '', 'disabled', ''],
            ['radio', 'mode', '到账方式', '', ['剩余余额', '代付余额'], '', '', 'disabled', ''],
            ['static', 'cash', '充值金额（元）'],
            ['static', 'order_id', '平台订单号'],
            ['textarea', 'remark', '本地备注[:无]', '', '', 'disabled', ''],
            ['static', 'other_order_id', '第三方订单号'],
            ['textarea', 'programmer_remark', '程序员备注[:无]', '', '', 'disabled', ''],
            ['static', 'operation_id', '操作号', '商户名称：' . get_user_nickname($info['operation_id'])],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];
        if ($this->no_auth) {
            unset($items[8]);
            unset($items[9]);
            unset($items[10]);
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id  id
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = CollectionModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }
        if (!in_array($info['status'], [0])) {
            $this->error('充值状态不是（申请充值）状态！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'Collection.edit');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }
            if ($data['status'] == 0) {
                $this->error('充值状态，请选择充值成功、驳回！');
            }
            if ($data['status'] == $info['status']) {
                $this->error('充值状态，请选择其它充值状态！');
            }
            if (in_array($data['status'], [1, 2])) {
                if (!$data['remark']) {
                    $this->error('请输入本地备注！');
                }
            }

            $data['operation_id'] = $this->merchant_id;
            if ($data['status'] == 1) {
                //
            }

            if (CollectionModel::update($data)) {

                $collection = CollectionModel::where('order_id', $data['order_id'])->find();

                // 记录行为
                action_log('payment_collection_edit', 'collection', $collection['order_id'], UID, json_encode($collection));

                // 充值成功
                if ($data['status'] == 1) {

                    try {
                        if ($collection['mode'] == 0) {
                            PaymentCashModel::where('merchant_id', $collection['merchant_id'])
                                ->inc('cash', $collection['cash'])
                                ->inc('sum_cash', $collection['cash'])
                                ->inc('count', 1)
                                ->update(['update_time' => time()]);
                        }
                        if ($collection['mode'] == 1) {
                            PaymentCashModel::where('merchant_id', $collection['merchant_id'])
                                ->inc('paid_cash', $collection['cash'])
                                ->inc('sum_cash', $collection['cash'])
                                ->inc('count', 1)
                                ->update(['update_time' => time()]);
                        }
                    } catch (\Exception $e) {
                        CollectionModel::where(['order_id' => $collection['order_id']])
                            ->update([
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(870000, $data, $e->getMessage());
                        $this->error("操作异常，请联系程序员处理：{$e->getMessage()}");
                    }
                }

                // 驳回
                if ($data['status'] == 2) {
                }

                $this->success('操作成功', url('index'));
            } else {
                payment_error_log(870001, $data);
                $this->error('操作失败，更新充值状态失败！', url('index'));
            }
        }

        $all_collection_status = [0 => '申请充值', 1 => '充值成功', 2 => '驳回'];
        $info['other_order_id'] = '1';
        $info['remark'] = '无';
        $items = [
            ['hidden', 'order_id', $id],
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            // ['static', 'out_name', '付款人姓名'],
            // ['static', 'out_card', '付款银行卡'],
            // ['static', 'enter_name', '收款人姓名'],
            // ['static', 'enter_card', '收款银行卡'],
            ['textarea', 'merchant_remark', '商户备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '充值状态', '', $all_collection_status, '', '', ''],
            ['radio', 'collection_type', '充值类型', '', ['银行卡', '支付宝'], '', '', 'disabled', ''],
            ['radio', 'mode', '到账方式', '', ['剩余余额', '代付余额'], '', '', 'disabled', ''],
            ['static', 'cashs', '充值金额（元）', '', $info['cash'] / 100],
            ['static', 'order_id', '本地订单号'],
            ['text', 'other_order_id', '第三方订单号', '类似银行交易号，做凭证', $info['remark']],
            ['textarea', 'remark', '本地备注', '', $info['remark']],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        $tips = "请勿填错！<br/>当商户申请充值后，您选择操作充值状态时，只能选择充值成功、驳回。<br/>"
            . "当您选择（驳回）的时候，只需输入备注信息即可。<br/>"
            . "当您选择（充值成功）的时候，输入第三方订单号（类似银行交易号），和备注信息即可。<br/>"
            . "当您选择（充值成功）的时候，系统将自动增加商户相对应的钱包余额。<br/>";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        //return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = CollectionModel::where('order_id', 'in', $ids)->column('order_id');
        return parent::setStatus($type, ['payment_collection_' . $type, 'payment_collection', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = CollectionModel::where('order_id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_collection_edit', 'payment_collection', $id, UID, $details]);
    }
}
